compio_io\framed\codec/serde_json.rs
1//! [`Encoder`]/[`Decoder`] implementation with serde_json
2//!
3//! This module provides a codec implementation for JSON serialization and
4//! deserialization using serde_json.
5//!
6//! # Examples
7//!
8//! ```
9//! use compio_io::framed::codec::{Decoder, Encoder, serde_json::SerdeJsonCodec};
10//! use serde::{Deserialize, Serialize};
11//!
12//! #[derive(Serialize, Deserialize)]
13//! struct Person {
14//! name: String,
15//! age: u32,
16//! }
17//!
18//! let mut codec = SerdeJsonCodec::new();
19//! let person = Person {
20//! name: "Alice".to_string(),
21//! age: 30,
22//! };
23//!
24//! // Encoding
25//! let mut buffer = Vec::new();
26//! codec.encode(person, &mut buffer).unwrap();
27//!
28//! // Decoding
29//! let decoded: Person = codec.decode(&buffer).unwrap();
30//! assert_eq!(decoded.name, "Alice");
31//! assert_eq!(decoded.age, 30);
32//! ```
33//!
34//! [`Encoder`]: crate::framed::codec::Encoder
35//! [`Decoder`]: crate::framed::codec::Decoder
36
37use std::io;
38
39use serde::{Serialize, de::DeserializeOwned};
40use thiserror::Error;
41
42use crate::framed::codec::{Decoder, Encoder};
43
44/// A codec for JSON serialization and deserialization using serde_json.
45///
46/// This codec can be configured to output pretty-printed JSON by setting the
47/// `pretty` flag.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub struct SerdeJsonCodec {
50 pretty: bool,
51}
52
53impl SerdeJsonCodec {
54 /// Creates a new `SerdeJsonCodec` with default settings (not
55 /// pretty-printed).
56 pub fn new() -> Self {
57 Self { pretty: false }
58 }
59
60 /// Creates a new `SerdeJsonCodec` with pretty-printing enabled.
61 pub fn pretty() -> Self {
62 Self { pretty: true }
63 }
64
65 /// Sets whether the JSON output should be pretty-printed.
66 pub fn set_pretty(&mut self, pretty: bool) -> &mut Self {
67 self.pretty = pretty;
68 self
69 }
70
71 /// Returns whether pretty-printing is enabled.
72 pub fn is_pretty(&self) -> bool {
73 self.pretty
74 }
75}
76
77impl Default for SerdeJsonCodec {
78 fn default() -> Self {
79 Self::new()
80 }
81}
82
83/// Errors that can occur during JSON encoding or decoding.
84#[derive(Debug, Error)]
85pub enum SerdeJsonCodecError {
86 /// Error from serde_json during serialization or deserialization.
87 #[error("serde-json error: {0}")]
88 SerdeJsonError(serde_json::Error),
89
90 /// I/O error during encoding or decoding.
91 #[error("IO error: {0}")]
92 IoError(#[from] io::Error),
93}
94
95impl<T: Serialize> Encoder<T> for SerdeJsonCodec {
96 type Error = SerdeJsonCodecError;
97
98 fn encode(&mut self, item: T, buf: &mut Vec<u8>) -> Result<(), Self::Error> {
99 if self.pretty {
100 serde_json::to_writer_pretty(buf, &item)
101 } else {
102 serde_json::to_writer(buf, &item)
103 }
104 .map_err(SerdeJsonCodecError::SerdeJsonError)
105 }
106}
107
108impl<T: DeserializeOwned> Decoder<T> for SerdeJsonCodec {
109 type Error = SerdeJsonCodecError;
110
111 fn decode(&mut self, buf: &[u8]) -> Result<T, Self::Error> {
112 serde_json::from_slice(buf).map_err(SerdeJsonCodecError::SerdeJsonError)
113 }
114}